package com.atguigu.gmall.order.controller;


import com.alibaba.fastjson.JSONObject;
import com.atguigu.gmall.cart.client.CartFeignClient;
import com.atguigu.gmall.common.result.Result;
import com.atguigu.gmall.common.util.AuthContextHolder;
import com.atguigu.gmall.model.cart.CartInfo;
import com.atguigu.gmall.model.order.OrderDetail;
import com.atguigu.gmall.model.order.OrderInfo;
import com.atguigu.gmall.order.service.OrderService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.util.CollectionUtils;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.math.BigDecimal;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.UUID;
import java.util.stream.Collectors;

@RestController
@RequestMapping("/api/order")
public class OrderApiController {

    @Autowired
    CartFeignClient cartFeignClient;

    @Autowired
    RedisTemplate redisTemplate;

    @Autowired
    OrderService orderService;

    @GetMapping("/trade")
    public Map<String,Object> trade(HttpServletRequest request){
        Map<String,Object> result = new HashMap();
        //商品清单
        List<CartInfo> cartInfoList = cartFeignClient.getCartListChecked();
        List<OrderDetail> orderDetailList = cartInfoList.stream().map(cartInfo -> {
            OrderDetail detail = new OrderDetail();
            detail.setImgUrl(cartInfo.getImgUrl());
            detail.setSkuName(cartInfo.getSkuName());
            detail.setOrderPrice(cartInfo.getCartPrice());
            detail.setSkuNum(cartInfo.getSkuNum());
            detail.setSkuId(cartInfo.getSkuId());
            return detail;
        }).collect(Collectors.toList());
        result.put("detailArrayList",orderDetailList);

        //总件数
        long sum = orderDetailList.stream().collect(Collectors.summarizingLong(OrderDetail::getSkuNum)).getSum();
        result.put("totalNum",sum);

        //总价格
        BigDecimal bigDecimal = new BigDecimal(0);
        for (OrderDetail detail : orderDetailList) {
            BigDecimal orderPrice = detail.getOrderPrice();
            bigDecimal = bigDecimal.add(orderPrice.multiply(new BigDecimal(detail.getSkuNum())));
        }
        result.put("totalAmount",bigDecimal);

        //交易号
        String uuid = UUID.randomUUID().toString().replace("-", "");
        String userId = AuthContextHolder.getUserId(request);
        redisTemplate.opsForValue().set("tradeNo:"+userId,uuid);
        result.put("tradeNo",uuid);

        return result;
    }

    //提交订单
    @PostMapping("/auth/submitOrder")
    public Result submitOrder(@RequestBody OrderInfo orderInfo , String tradeNo , HttpServletRequest request){
        String userId = AuthContextHolder.getUserId(request);
        if (StringUtils.isEmpty(tradeNo)) {
            return Result.fail().message("非法操作");
        }
        Object o = redisTemplate.opsForValue().get("tradeNo:" + userId);
        if (o == null){
            return Result.fail().message("请误重复提交订单");
        } else if (!tradeNo.equals(o)) {
            return Result.fail().message("非法操作");
        }

        redisTemplate.delete("tradeNo:" + userId);
        List<OrderDetail> orderDetailList = orderInfo.getOrderDetailList();
        if (!CollectionUtils.isEmpty(orderDetailList)){
            for (OrderDetail orderDetail : orderDetailList) {
                boolean flag = orderService.hasStock(orderDetail.getSkuId(),orderDetail.getSkuNum());
                if (!flag) {
                    return Result.fail().message(orderDetail.getSkuName()+"[此商品已经售完]");
                }
            }
        }
        orderInfo.setUserId(Long.parseLong(userId));
        Long orderId = orderService.submitOrder(orderInfo);
        return Result.ok(orderId);
    }

    @GetMapping("/getOrderInfo/{orderId}")
    public OrderInfo getOrderInfo(@PathVariable Long orderId){
        return orderService.getOrderInfo(orderId);
    }

    @PostMapping("/orderSplit")
    public String orderSplit(Long orderId , String wareSkuMap){
       List<Map> listMap =  orderService.orderSplit(orderId,wareSkuMap);
       return JSONObject.toJSONString(listMap);
    }
}
